<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="组织名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入组织名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="组织类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请输入组织类型">
          <el-option v-for="(item, index) in orgTypeList" :key="index" :label="item.dictLabel"
            :value="item.dictValue"></el-option>
        </el-select>
        <!-- <el-input v-model="queryParams.type" placeholder="请输入组织类型" clearable @keyup.enter.native="handleQuery" /> -->
      </el-form-item>

      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="queryParams.contactName" placeholder="请输入联系人姓名" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="所在区域" prop="region">
        <el-select v-model="queryParams.region" placeholder="请选择所在区域">
          <el-option v-for="(item, index) in regionList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
        <!-- <el-input v-model="queryParams.region" placeholder="请输入所在区域" clearable @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:org:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:org:export']">导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleImport"
          v-hasPermi="['system:org:export']">批量导入</el-button>
      </el-col>
      <div style="display: flex;gap: 10px;">
        <div v-for="(item, index) in regionStatistics" :key="index">
          {{ item.regionName }}：{{ item.count }}个组织
        </div>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orgList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="组织名称" align="center" prop="name" />

      <el-table-column label="组织类型" align="center" prop="type">
        <template slot-scope="scope">
          {{orgTypeList.find(item => item.dictValue == scope.row.type).dictLabel}}
        </template>
      </el-table-column>

      <el-table-column label="所在区域" align="center" prop="region" />
      <el-table-column label="成员人数" align="center" prop="memberCount" />
      <el-table-column label="联系人" align="center" prop="contactName" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="组织地址" align="center" prop="address" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:org:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdatePassword(scope.row)"
            v-hasPermi="['system:org:edit']">修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改组织对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="组织名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="logo" prop="logo">
          <image-upload :limit="1" v-model="form.logo" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="组织类型" prop="type">
          <!-- <el-input v-model="form.type" placeholder="请输入组织类型" /> -->
          <el-select v-model="form.type" placeholder="请输入组织类型">
            <el-option v-for="(item, index) in orgTypeList" :key="index" :label="item.dictLabel"
              :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在区域" prop="region">
          <!-- <el-input v-model="form.region" placeholder="请输入所在区域" /> -->
          <el-select v-model="form.region" placeholder="请输入组织类型">
            <el-option v-for="(item, index) in regionList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入组织地址" />
        </el-form-item>
        <!-- 如果是新增有创建账号，密码，确认密码 -->
        <el-form-item v-if="!form.id" label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" placeholder="请输入确认密码" />
        </el-form-item>
        <el-form-item label="组织简介">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordOpen" width="400px" append-to-body>
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="passwordForm.userName" placeholder="请输入账号" :disabled="true" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" placeholder="请输入新密码" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" type="password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
        <el-button @click="cancelPassword">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量导入组织" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getUser, resetPwd } from "@/api/system/user";
import { listOrg, getOrg, delOrg, addOrg, updateOrg, orgTypeList, statisticsByRegion } from "@/api/system/org";

export default {
  name: "Org",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组织表格数据
      orgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示修改密码弹出层
      passwordOpen: false,
      // 是否显示导入弹出层
      importOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inviteCode: null,
        name: null,
        logo: null,
        contactName: null,
        contactPhone: null,
        type: null,
        region: null,
        address: null,
        content: null,
      },
      // 表单参数
      form: {},
      // 密码表单参数
      passwordForm: {
        userId: '',
        userName: '',
        password: '',
        confirmPassword: ''
      },
      // 表单校验
      rules: {
      },
      // 密码表单校验
      passwordRules: {
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" }
        ]
      },
      orgTypeList: [],
      // 上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/encounter/org/importData"
      },
      regionStatistics: [],
      regionList: ['黄石港区', '西塞山区', '大冶湖高新区', '下陆区', '开铁区', '阳新县', '大冶市']
    };
  },
  created() {
    this.getList();
    this.getOrgTypeList();
    this.getRegionStatistics();
  },
  methods: {
    // 确认密码校验
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    /** 查询组织列表 */
    getList() {
      this.loading = true;
      listOrg(this.queryParams).then(response => {
        this.orgList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getOrgTypeList() {
      orgTypeList().then(response => {
        this.orgTypeList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    upload: {
      // 是否显示弹出层
      open: false,
      // 是否禁用上传
      isUploading: false,
      // 设置上传的请求头部
      headers: { Authorization: "Bearer " + getToken() },
      // 上传的地址
      url: process.env.VUE_APP_BASE_API + "/encounter/org/importData"
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inviteCode: null,
        name: null,
        logo: null,
        contactName: null,
        contactPhone: null,
        type: null,
        region: null,
        address: null,
        content: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加组织";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrg(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改组织";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrg(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrg(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除组织编号为"' + ids + '"的数据项？').then(function () {
        return delOrg(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/org/export', {
        ...this.queryParams
      }, `org_${new Date().getTime()}.xlsx`)
    },
    handleUpdatePassword(row) {
      this.resetPasswordForm();
      this.passwordForm.userId = row.adminUserId;
      this.passwordOpen = true;
      getUser(row.adminUserId).then(response => {
        this.passwordForm.userName = response.data.userName; // 使用组织名称作为账号显示
      });
    },
    // 重置密码表单
    resetPasswordForm() {
      this.passwordForm = {
        userId: '',
        userName: '',
        password: '',
        confirmPassword: ''
      };
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.resetFields();
      }
    },
    // 取消修改密码
    cancelPassword() {
      this.passwordOpen = false;
      this.resetPasswordForm();
    },
    // 提交修改密码
    submitPasswordForm() {
      this.$refs["passwordForm"].validate(valid => {
        if (valid) {
          // 调用修改密码接口
          const data = {
            userId: this.passwordForm.userId,
            userName: this.passwordForm.userName,
            password: this.passwordForm.password
          };
          resetPwd(data).then(res => {
            if (res.code == 200) {
              this.$modal.msgSuccess("密码修改成功");
              this.passwordOpen = false;
              this.resetPasswordForm();
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        }
      });
    },
    handleImport() {
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const fileUrl = require('@/assets/xlsxTemplate/stationTemplate.xlsx')
      const link = document.createElement('a')
      link.href = fileUrl
      link.download = '招聘岗位管理-数据导入模板.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code === 200) {
        this.$modal.msgSuccess("导入成功");
        this.getList();
        this.getStationCount()
      } else {
        this.$modal.msgError("导入失败");
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      }
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 区域统计
    getRegionStatistics() {
      statisticsByRegion().then(response => {
        this.regionStatistics = response.data;
      });
    },
  }
};
</script>
